import request from '@/utils/request'

/**
 * 基础字典数据加载工具类
 * 统一管理系统中所有的基础类型数据
 */
export class DictionaryLoader {
  constructor() {
    this.cache = new Map() // 缓存已加载的数据
  }

  /**
   * 加载基础字典数据
   * @param {Array} types 需要加载的字典类型数组
   * @returns {Promise<Object>} 返回包含所有字典数据的对象
   */
  async loadDictionaries(types = []) {
    const results = {}
    const promises = []

    // 为每个类型创建加载Promise
    types.forEach(type => {
      if (this.cache.has(type.key)) {
        // 如果缓存中有数据，直接使用
        results[type.key] = this.cache.get(type.key)
      } else {
        // 否则创建加载Promise
        const promise = this.loadSingleDictionary(type)
          .then(data => {
            this.cache.set(type.key, data)
            results[type.key] = data
            return data
          })
          .catch(error => {
            console.error(`加载${type.name}失败:`, error)
            results[type.key] = []
            return []
          })
        promises.push(promise)
      }
    })

    // 等待所有Promise完成
    await Promise.all(promises)
    return results
  }

  /**
   * 加载单个字典数据
   * @param {Object} type 字典类型配置
   * @returns {Promise<Array>} 返回字典数据数组
   */
  async loadSingleDictionary(type) {
    try {
      const response = await request({
        url: type.url,
        method: 'get',
        params: { pageNum: 1, pageSize: 9999, enabled: 1 }
      })
      return response.rows || response.data || []
    } catch (error) {
      console.error(`加载${type.name}失败:`, error)
      return []
    }
  }

  /**
   * 清除缓存
   */
  clearCache() {
    this.cache.clear()
  }

  /**
   * 清除指定类型的缓存
   * @param {string} key 字典类型key
   */
  clearCacheByKey(key) {
    this.cache.delete(key)
  }

  /**
   * 刷新指定类型的字典数据
   * @param {string} key 字典类型key
   * @returns {Promise<Array>} 返回刷新后的字典数据
   */
  async refreshDictionary(key) {
    this.clearCacheByKey(key)
    const type = Object.values(DICTIONARY_TYPES).find(t => t.key === key)
    if (type) {
      const data = await this.loadSingleDictionary(type)
      this.cache.set(key, data)
      return data
    }
    return []
  }

  /**
   * 刷新所有字典数据
   * @returns {Promise<Object>} 返回所有刷新后的字典数据
   */
  async refreshAllDictionaries() {
    this.clearCache()
    const allTypes = Object.values(DICTIONARY_TYPES)
    return await this.loadDictionaries(allTypes)
  }
}

// 预定义的字典类型配置
export const DICTIONARY_TYPES = {
  // 设备类型
  EQUIPMENT_TYPE: {
    key: 'equipmentTypes',
    name: '设备类型',
    url: '/system/type/list'
  },
  // 报修类型
  REPORT_TYPE: {
    key: 'reportTypes',
    name: '报修类型',
    url: '/system/report/type/list'
  },
  // 故障类型
  FAULT_TYPE: {
    key: 'faultTypes',
    name: '故障类型',
    url: '/system/fault/type/list'
  },
  // 紧急程度
  URGENCY_LEVEL: {
    key: 'urgencyLevels',
    name: '紧急程度',
    url: '/system/level/list'
  },
  // 备件类型
  PART_TYPE: {
    key: 'partTypes',
    name: '备件类型',
    url: '/system/part/type/list'
  },
  // 备件仓库
  WAREHOUSE: {
    key: 'warehouses',
    name: '备件仓库',
    url: '/system/warehouse/list'
  }
}

// 创建全局实例
export const dictionaryLoader = new DictionaryLoader()

// 便捷方法：加载常用的字典数据组合
export const loadCommonDictionaries = () => {
  return dictionaryLoader.loadDictionaries([
    DICTIONARY_TYPES.EQUIPMENT_TYPE,
    DICTIONARY_TYPES.REPORT_TYPE,
    DICTIONARY_TYPES.FAULT_TYPE,
    DICTIONARY_TYPES.URGENCY_LEVEL
  ])
}

// 便捷方法：加载报修相关的字典数据
export const loadRepairDictionaries = () => {
  return dictionaryLoader.loadDictionaries([
    DICTIONARY_TYPES.EQUIPMENT_TYPE,
    DICTIONARY_TYPES.REPORT_TYPE,
    DICTIONARY_TYPES.FAULT_TYPE,
    DICTIONARY_TYPES.URGENCY_LEVEL
  ])
}

// 便捷方法：加载盘点相关的字典数据
export const loadInventoryDictionaries = () => {
  return dictionaryLoader.loadDictionaries([
    DICTIONARY_TYPES.PART_TYPE,
    DICTIONARY_TYPES.WAREHOUSE
  ])
}

// 便捷方法：刷新指定类型的字典数据
export const refreshDictionary = (key) => {
  return dictionaryLoader.refreshDictionary(key)
}

// 便捷方法：刷新所有字典数据
export const refreshAllDictionaries = () => {
  return dictionaryLoader.refreshAllDictionaries()
}
